use std::fs::File;
use std::io::ErrorKind;
use std::io::Read;
use std::result::Result;
#[test]
pub fn result_demo() {
    let r = File::open("hello.txt");
    let f = match r {
        Ok(f) => f,
        Err(error) => panic!("Error opening file{:?}", error),
    };
}
#[test]
pub fn result_demo2() {
    let r = File::open("hello.txt");
    let f = match r {
        Result::Ok(f) => f,
        Result::Err(error) => match error.kind() { //打开文件错误，获取错误类型
            //如果是文件不存在,则创建文件
            ErrorKind::NotFound => match File::create("hello.txt") {
                Ok(fc) => fc, //创建成功
                Err(e) => panic!("Error creating file:{:?}", e),
            },
            //其他错误类型
            other_error => panic!("Error opening the file:{:?}", other_error),
        },
    };
}

pub fn result_demo3() {
    //打开成功直接返回，失败则panic
    let f = File::open("hello.txt").unwrap();
}

pub fn result_demo4() {
    //打开成功直接返回，失败则panic,自定义错误信息
    let f = File::open("hello.txt").expect("无法打开文件");
}

//读取文件内容，传递错误
fn read_msg_from_file() -> Result<String, std::io::Error> {
    let r = File::open("hello.txt");
    let mut f = match r {
        Ok(file) => file,
        Err(e) => return Err(e),
    };

    let mut s = String::new();
    match f.read_to_string(&mut s) {
        Ok(_) => Ok(s),
        Err(e) => Err(e),
    }
}
//读取文件内容，传递错误 通过?简化
fn read_msg_from_file2() -> Result<String, std::io::Error> {
    let mut f = File::open("hello.txt")?;
    let mut s = String::new();
    f.read_to_string(&mut s)?;
    Ok(s)
}

pub fn result_demo5() {
    //let result = read_msg_from_file();
    let result = read_msg_from_file2();
    match result {
        Ok(s) => println!("{}", s),
        Err(e) => panic!("{:?}", e),
    };
}
